<script setup>
import {request} from "@/util/request.js";
import {ref} from "vue";
import {useUserStore} from "@/store/user.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {formatterDateTime} from "@/util/utils.js";

const products = ref([]);
const userStore = useUserStore()

const config = {
    headers: {
        'Authorization': userStore.token
    }
}
function getProducts() {
    // 获取商品信息
    request.get("/product/list", config).then(res => {
        if (res.code === 1) {
            products.value = res.data
        } else {
            ElMessage.error(res.msg)
        }
    })
}

getProducts()
// 查询条件
const product = ref({
    name: '',
    productId: undefined,
    price: undefined,
    stock: undefined
})

// 搜索
function handleSearch() {
    request.get("/product/list")
}

// 重置
function handleReset() {
    product.value = {
        name: '',
        productId: undefined,
        price: undefined,
        stock: undefined
    }
}

// 格式化日期显示
function formatterTime(row, column, cellValue, index) {
    return formatterDateTime(new Date(cellValue))
}

// 删除操作
function handleDelete(index, row) {
    request.get("/product/delete/" + row.productId, config).then(res => {
        if (res.code === 1) {
            ElMessage.success("删除成功");
        } else {
            ElMessage.error("删除失败");
        }
    })
}

// 修改操作
const editProduct = ref({}) // 记录修改的商品信息
function handleEdit(row) {
    dialogVisible.value = true
    editProduct.value = row
}

// 控制 修改页面的显示
const dialogVisible = ref(false)


function handleClose() {
    ElMessage.info("取消修改")
    dialogVisible.value = false
}

// 提交修改
function submitEdit() {
    request.post('/product/edit', editProduct.value, config).then(res => {
        if (res.code === 1) {
            ElMessage.success('修改成功')
        } else {
            ElMessage.error(res.msg)
        }
    })
}

// 商品图片
const previewVisible = ref(false)
const previewProduct = ref({})

// 关闭预览
function previewClose() {
    previewVisible.value = false
    getProducts()
}

// 查看更多商品图
const images = ref([])

function moreImage(row) {
    previewVisible.value = true
    previewProduct.value = row
    request.get("/product/list/images/" + row.productId, config)
        .then(res => {
            if (res.code === 1) {
                images.value = res.data.map(item => ({
                    url: '/api' + item.imageUrl,
                    name: item.imageName,
                    status: 'finished',
                    id: item.imageId,
                    isPrimary: item.isPrimary
                }));
            } else {
                images.value = []
                ElMessage.error(res.msg)
            }
        })
}

const bigPreviewVisible = ref(false)
const previewImage = ref('')

function pictureCardPreview(file) {
    bigPreviewVisible.value = true
    previewImage.value = file.url
}

const uploadConfig = {
    headers: {
        'Authorization': userStore.token,
        'Content-Type': 'multipart/form-data'
    }
}

// 上传文件之前触发，return false 可以组织默认上传事件，因为我们在这里处理上传
function beforeUpload(file) {
    ElMessageBox.prompt('请输入商品图片名称', 'Tips', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
    })
        .then(({value}) => {
            ElMessage({
                type: 'warning',
                message: `开始上传图片: ${value}`
            })
            request.post('/product/upload', {
                file: file,
                productId: previewProduct.value.productId,
                name: value
            }, uploadConfig).then(res => {
                console.log(res)
                if (res.code === 1) {
                    ElMessage.success("图片上传成功")
                    moreImage(previewProduct.value)
                } else {
                    ElMessage.error(res.msg)
                }
            }).catch(err => {
                console.log(err)
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '输入取消',
            })
        })
    return false
}

function beforeRemove(file) {
    ElMessageBox.confirm("确认要删除？").then(() => {
        remove(file)
    }).catch(() => {
        ElMessage.info("取消删除！")
    })
    return false;
}

function remove(file) {
    request.get('/product/delete/image/' + file.id, config)
        .then(res => {
            if (res.code === 1) {
                ElMessage.success("删除成功")
                moreImage(previewProduct.value)
            } else {
                ElMessage.error(res.msg)
            }
        })
}

// 设置主图
function editPrimary(file) {
    ElMessageBox.confirm("确认要设置当前图片为主图吗？", "tips").then(() => {
        console.log(file)
        request.get('/product/edit/image/primary/' + previewProduct.value.productId + '/' + file.id, config)
            .then(res => {
                if (res.code === 1) {
                    ElMessage.success("设置成功")
                    moreImage(previewProduct.value)
                } else {
                    ElMessage.error(res.msg)
                }
            })
    }).catch(() => {
        ElMessage.info("取消设置")
    })
}

</script>
<!--商品管理-->
<template>
    <el-row>
        <el-col>
            <!--按照条件查找-->
            <el-form label-width="80px" size="large" :model="product">
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="商品名称">
                            <el-input v-model="product.name" placeholder="请输入商品名称"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="商品编号">
                            <el-input v-model="product.productId" placeholder="请输入商品编号"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" :offset="2">
                        <el-button type="primary" size="default" @click="handleSearch">搜索</el-button>
                        <el-button type="warning" size="default" @click="handleReset">重置</el-button>
                    </el-col>
                </el-row>
            </el-form>
            <!--商品详情表格-->
            <el-table
                :data="products"
                style="width: 100%; margin-bottom: 20px"
                row-key="productId">
                <el-table-column label="编号" prop="productId" sortable/>
                <el-table-column label="名称" prop="name"/>
                <el-table-column label="单价" prop="price" sortable/>
                <el-table-column label="库存" prop="stock" sortable/>
                <el-table-column label="单位" prop="unit"/>
                <el-table-column label="默认图" prop="defaultImage" width="240">
                    <template #default="scope">
                        <el-image @click="moreImage(scope.row)"
                                  :src="scope.row.defaultImage ? '/api' + scope.row.defaultImage.imageUrl : ''"
                                  class="product_image">
                            <template #error>
                                <el-button type="danger" size="small" plain @click="moreImage(scope.row)">
                                    暂无图片，点击上传
                                </el-button>
                            </template>
                        </el-image>
                    </template>
                </el-table-column>
                <el-table-column label="状态" prop="status">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === '1'?'success' : 'danger'" size="small">
                            {{ scope.row.status === '1' ? '上架' : '下架' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" width="180" prop="createdAt" sortable :formatter="formatterTime"/>
                <el-table-column label="操作" width="240">
                    <template #default="scope">
                        <el-button type="danger" size="small" @click="handleDelete(scope.$index, scope.row)">删除
                        </el-button>
                        <el-button type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-col>
    </el-row>

    <!--修改商品信息-->
    <el-dialog
        v-model="dialogVisible"
        title="修改商品信息"
        width="50%"
        :before-close="handleClose">
        <el-form label-width="80px" size="large">
            <el-form-item label="商品名称">
                <el-input v-model="editProduct.name"/>
            </el-form-item>
            <el-form-item label="商品数量">
                <el-input-number
                    v-model="editProduct.stock"
                    :min="1"
                    controls-position="right"
                />
            </el-form-item>
            <el-form-item label="商品单价">
                <el-input-number v-model="editProduct.price" :precision="2" :step="1"/>
            </el-form-item>
            <el-form-item label="状态">
                <el-radio-group v-model="editProduct.status" class="ml-4">
                    <el-radio :label="'0'" size="large">下架</el-radio>
                    <el-radio :label="'1'" size="large">上架</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="商品描述">
                <el-input type="textarea" v-model="editProduct.details"/>
            </el-form-item>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">
          确认
        </el-button>
      </span>
        </template>
    </el-dialog>

    <!--商品图片-->
    <el-dialog
        v-model="previewVisible"
        title="商品图片"
        width="40%"
        :before-close="previewClose">
        <el-upload
            v-model:file-list="images"
            action="#"
            list-type="picture-card"
            :on-preview="pictureCardPreview"
            :before-upload="beforeUpload"
            :before-remove="beforeRemove"
            accept="image/*">
            <el-tooltip
                class="box-item"
                effect="light"
                content="上传图片"
                placement="bottom"
                :hide-after="0"
            >
                <el-icon><Plus/></el-icon>
            </el-tooltip>
            <template #file="{file}">
                <img :src="file.url" class="el-upload-list__item-thumbnail"/>
                <div class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="pictureCardPreview(file)">
                        <el-tooltip
                            class="box-item"
                            effect="light"
                            content="查看大图"
                            placement="bottom"
                            :hide-after="0"
                        >
                            <el-icon><zoom-in/></el-icon>
                        </el-tooltip>
                    </span>
                    <span v-if="images.length !== 0" class="el-upload-list__item-delete" @click="beforeRemove(file)">
                        <el-tooltip
                            class="box-item"
                            effect="light"
                            content="删除图片"
                            placement="bottom"
                            :hide-after="0"
                        >
                            <el-icon><Delete/></el-icon>
                        </el-tooltip>
                    </span>
                    <span v-if="!file.isPrimary" class="el-upload-list__item-delete">
                        <!--修改主图-->
                        <el-tooltip
                            class="box-item"
                            effect="light"
                            content="设置为主图"
                            placement="bottom"
                            :hide-after="0"
                        >
                            <el-switch @change="editPrimary(file)"/>
                        </el-tooltip>
                    </span>
                </div>
                <span v-if="file.isPrimary">
                    <el-tag class="ml-2 badge" type="success">主图</el-tag>
                </span>
                <span v-else>
                    <el-tag class="ml-2 badge" type="warning">副图</el-tag>
                </span>
            </template>
        </el-upload>

        <el-dialog v-model="bigPreviewVisible">
            <el-image w-full
                      :src="previewImage"
                      alt="Preview Image"
                      fit="cover"
            />
        </el-dialog>
    </el-dialog>


</template>

<style scoped>
.product_image {
    height: 60px;
}

.product_image {
    line-height: 60px;
}

.cell {
    text-align: center !important;
}

.badge {
    padding: 2px 6px;
    position: absolute;
    top: 5px;
    right: 5px;
}
</style>